// 使用这个库可以添加的请求头（比如添加token）
import { EventSourcePolyfill } from "event-source-polyfill";
import { getToken } from '@/utils/user'
export default {
  data() {
    return {
      eventSource: null
    }
  },
  mounted() {
    this.createSSE()
  },
  methods: {
    createSSE(){
      if(window.EventSource){
        // 根据环境的不同，变更url
        const url = process.env.VUE_APP_MSG_SERVER_URL
        // 用户userId
        const { userId } = this.$store.state.user
        this.eventSource = new EventSourcePolyfill(
          `${url}/sse/connect/${userId}`, {
          // 设置重连时间
          heartbeatTimeout: 60 * 60 * 1000,
          // 添加token
          headers: {
             'Authorization': `Bearer ${getToken()}`,
          },
        });
        this.eventSource.onopen = (e) => {
          console.log("已建立SSE连接~")
        }
        this.eventSource.onmessage = (e) => {
          console.log("已接受到消息:", e.data)
        }
        this.eventSource.onerror = (e) => {
          if (e.readyState == EventSource.CLOSED) {
            console.log("SSE连接关闭");
          } else if (this.eventSource.readyState == EventSource.CONNECTING) {
            console.log("SSE正在重连");
            //重新设置token
            this.eventSource.headers = {
              'Authorization': `Bearer ${getToken()}`
            };
          } else {
            console.log('error', e);
          }
        };
      } else {
        console.log("你的浏览器不支持SSE~")
      }
    },
    beforeDestroy() {
      if(this.eventSource){
          const { userId } = this.$store.state.user
          // 关闭SSE
          this.eventSource.close();
          // 通知后端关闭连接
          this.$API.system.msg.closeSse(userId)
          this.eventSource = null
          console.log("退出登录或关闭浏览器，关闭SSE连接~")
       }
    }